package com.easyedu.gateway.Filter;

import com.alibaba.fastjson.JSONObject;
import com.easyedu.core.redis.RedisUtils;
import com.easyedu.core.util.JwtUtils;
import com.easyedu.core.util.R;
import com.easyedu.core.util.ResponseCode;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URLDecoder;
import java.util.Map;

/**
 * @author lmr
 **/
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    private static final String TOKEN = "token";
    private static final String LOGIN_URL = "/root/login";
    private static final String ROOT_URL = "/dean/index";
    private final JwtUtils jwtUtils = new JwtUtils();

    private final RedisUtils redisUtils;

    public AuthorizeFilter(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }


    @SneakyThrows
    @Order(0)
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //放行路径
        if (path.equals("/root/logon")
                || path.equals("/root/check/user/name")
                || path.equals("/root/check/user/number")) {
            return chain.filter(exchange);
        }
        String token = null;
        //验证是否可以进行登录
        if (path.equals(LOGIN_URL)) {
            HttpCookie httpCookie = request.getCookies().getFirst(TOKEN);
            if (httpCookie != null) {
                token = URLDecoder.decode(httpCookie.getValue(), "UTF-8");
            }else{
                return chain.filter(exchange);
            }
        }
        if (token == null){
            HttpHeaders headers = request.getHeaders();
            token = headers.getFirst(TOKEN);
        }
        LOGGER.info("[token] " + token);
        if (token == null) {
            return response.writeWith(Flux.just(this.wrongLogin(response, "不存在token")));
        }
        Map<String, String> msgFromToken = jwtUtils.getMsgFromJwt(token);
        long userNumber;
        if (!msgFromToken.containsKey("userNumber")) {
            return response.writeWith(Flux.just(this.wrongLogin(response, "非法token")));
        }
        userNumber = Long.parseLong(msgFromToken.get("userNumber"));
        LOGGER.info("[userNumber] " + userNumber);
        try {
            String redisToken = redisUtils.get("userLoginToken" + userNumber);
            if (!redisToken.equals(token)) {
                return response.writeWith(Flux.just(this.wrongLogin(response, "非法token")));
            }
        } catch (NullPointerException e) {
            LOGGER.info("[login] 登录已过期,请重新登录");
            return response.writeWith(Flux.just(this.wrongLogin(response, "登录已过期,请重新登录")));
        }

        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }


    private DataBuffer redirect(ServerHttpResponse response, String msg, String redirectUrl) {
        return response.bufferFactory().wrap(JSONObject.toJSONBytes(R.error(ResponseCode.REDIRECT).message(msg).data(
                "url", redirectUrl)));
    }

    private DataBuffer wrongLogin(ServerHttpResponse response, String msg){
        return response.bufferFactory().wrap(JSONObject.toJSONBytes(R.error().message(msg)));
    }
}
